package cn.edu.njust.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

/**
 * 登录验证 过滤器
 */
//@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        //判断访问资源路径是否和登录注册相关
        String[] urls = {"/login.html","/image/","/css/","/js/","/register.html","/systemControl",};
        // 获取当前访问的资源路径
        String url = req.getRequestURL().toString();
        String s = req.getRequestURI();
        //循环判断
        for (String u : urls) {
            if(url.contains(u) || "/DormitoryCheckSystem/".equals(s)){
                //放行
                chain.doFilter(request, response);
                return;
            }
        }
        //1. 判断session中是否有user
        HttpSession session = req.getSession();
        Object user = session.getAttribute("loginUser");

        //2. 判断user是否为null
        if(user != null){
            // 登录过了 放行
            chain.doFilter(request, response);
        }else {
            // 没有登陆，存储提示信息，跳转到登录页面
            req.setAttribute("login_msg","您尚未登陆！");
            req.getRequestDispatcher("/login.html").forward(req,response);
        }
    }
}
